<?php
/**
 * @class news News module
 * @author Bethrezen <admin@devgroup.ru>
 * @desc Handles all news related stuff.
 */
class news
{
	var $core;
	
	var $tableName = 't_news';
	
	var $action='';
	
	//! Constructor
	function news(&$_core)
	{
		
		
		$this->core = $_core;
		
		$this->core->adminLinks['news'] = 'Новости';
		
		if (!file_exists(DB_DIR . $this->core->config->dbName . "/" . $this->tableName . ".txt"))
		{
		
			$SQL = "CREATE TABLE " . $this->tableName . " ( id inc , title str , content str , full str , date str , url str )";
			
			$this->core->db->executeQuery($SQL);
			
			$this->core->db->executeQuery("INSERT INTO " . $this->tableName . " ( title , content , full , date , url ) VALUES ( 'Съешь же ещё этих мягких французских булок, да выпей чаю' , 'Это тестовая новость' , 'Много-много буков' , '" . time() . "' , '" .  $this->core->translitUrl('Съешь же ещё этих мягких французских булок, да выпей чаю') . "' )");
		}
		
		$action = 'main';
		if (isset($_GET['actionNews']))
			$action = $_GET['actionNews'];
		if (isset($_POST['actionNews']))
			$action = $_POST['actionNews'];
				
		$this->action = $action;
		
	}
	
	//! Makes an URL for show action
	function makeShowUrl($data)
	{
		if ($this->core->config->useModRewrite)
		{
			$year = strftime("%Y", $data['date']);
			$month = strftime("%m", $data['date']);
			$day = strftime("%d", $data['date']);
			return $this->core->getDirectoryName() . "/news/show/$year/$month/$day/" . $data['url'] . ".html";
		}
		else
		{
			$year = strftime("%Y", $data['date']);
			$month = strftime("%m", $data['date']);
			$day = strftime("%d", $data['date']);
			return basename($_SERVER['SCRIPT_NAME']) . "?action=news&actionNews=show&year=$year&month=$month&day=$day&p=".$data['url'];
		}
	}
	
	//! Makes URL for Archive action
	function makeArchiveUrl()
	{
		if ($this->core->config->useModRewrite)
		{
			return $this->core->getDirectoryName() . "/news/archive.html";
		}
		else
		{
			
			return basename($_SERVER['SCRIPT_NAME']) . "?action=news&actionNews=archive";
		}
	}
	
	/**
	 * Returns TOP-$limit News
	 *
	 */
	function getTopNewsList($limit=10)
	{
	
		$records = array();
		$q4news = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " ORDER BY date DESC LIMIT $limit ");
		if ($q4news->getRowCount() != 0)
		{
			while ($q4news->next())
			{
				$record = $q4news->getCurrentValuesAsHash();
				$record['content'] = preg_replace("/##(.+)##/i", "<a href=\"" . $this->makeShowUrl($record) . "\">\\1</a>", $record['content']);
				$record['date'] = date("d.m.y H:i",$record['date']);
				$records[] = $record;
			}
		}
		
		return ($records);
	}
	
	/**
	 * Returns news archive
	 */
	function getNewsArchive()
	{
		$records = array();
		$q4news = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " ORDER BY date DESC ");
		if ($q4news->getRowCount() != 0)
		{
			while ($q4news->next())
			{
				$record = $q4news->getCurrentValuesAsHash();
				$record['content'] = preg_replace("/##(.+)##/i", "<a href=\"" . $this->makeShowUrl($record) . "\">\\1</a>", $record['content']);
				$record['content'] = preg_replace("/##(.+)##/i", "<a href=\"" . $this->makeShowUrl($record) . "\">\\1</a>", $record['content']);
				$record['year'] = date("Y",$record['date']);
				$record['date'] = date("d.m", $record['date']);
				$records[] = $record;
			}
		}
		
		return ($records);
	
	}
	
	/**
	 * Returns the detailed news.
	 *
	 */
	function getNews($p)
	{
		$record = null;
		$q4news = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " WHERE url='".urlencode($p)."'");
		
		if ($q4news->getRowCount() != 0)
		{
			$q4news->next();
			
				$record = $q4news->getCurrentValuesAsHash();
				$record['date'] = date("d.m.y H:i",$record['date']);
			
			
		}
		
		return ($record);
	}
	
	/**
	 * Main admin action
	 *
	 */
	function admin()
	{
		
		$actFunc = "admin" . $this->action;
		$this->$actFunc();
	}
	
	//! Main admin action
	function adminMain()
	{	
		
		$q4news = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " ORDER BY date DESC  ");
		if ($q4news->getRowCount() != 0)
		{
			?>
			<h2>Новости</h2>
			<table cellpadding="0" cellspacing="2" border="0"><TR><TD>Дата</TD><td>Заголовок</td><td>Действия</td></TR>
			
			<?php
		
			while ($q4news->next())
			{
				$record = $q4news->getCurrentValuesAsHash();
				?>
				<tr><TD><?=date("d.m.y H:i",$record['date']);?></TD><TD><?=$record['title'];?></TD><TD><a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=news&actionNews=Edit&id=<?=$record['id']?>">Редактировать</a> <a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=news&actionNews=Remove&id=<?=$record['id']?>">Удалить</a></TD></tr>
				<?php
			}	
				
			?>
			</table>
			<a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=news&actionNews=Add">Добавить</a>
			<?php
		}
		
	}
	
	//! Remove news
	function adminRemove()
	{
		if (isset($_GET['id']))
		{
			$SQL = "DELETE FROM " . $this->tableName . " WHERE  id   = '" . intval($_GET['id']) . "' ";
			
				$this->core->db->executeQuery($SQL);
		}
		
		$this->adminMain();
	}
	
	//! Edit news
	function adminEdit()
	{
		if (isset($_GET['id']))
		{
			$q4edit = $this->core->db->executeQuery("SELECT * FROM " . $this->tableName . " WHERE id = '" . intval($_GET['id']) . "'");
			if ($q4edit->getRowCount() != 0)
			{
				$q4edit->next();
				$record = $q4edit->getCurrentValuesAsHash();
				?>
				<h2>Редактировать новость</h2>
		<form action="<?=basename($_SERVER['SCRIPT_FILENAME']);?>" method="POST">
		<input type="hidden" name="actAdmin" value="news">
		<input type="hidden" name="actionNews" value="Edit">
		<input type="hidden" name="id" value="<?=$record['id'];?>">
		<table cellspacing="2" cellpadding="0" border="0">
		<TR><TD>Заголовок:</TD><TD><input type="text" name="title" value="<?=$record['title'];?>"></TD></TR>
		<TR><TD>Текст:</TD><TD><textarea name="content"><?=$record['content'];?></textarea></TD></TR>
		<TR><TD>Расширенный текст:</TD><TD><textarea name="full"><?=$record['full'];?></textarea></TD></TR>
		<TR><TD>URL:</TD><TD><input type="text" name="url" value="<?=$record['url'];?>"> (пусто для автоматической транслитеризации)</TD></TR>
		<TR><TD>Редактирование:</TD><TD><input type="submit" value="Сохранить"></TD></TR>
		</table>
		</form><br />
		<a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=news">Назад в новости</a>
				<?php
			
			}
			
		}
		if (isset($_POST['id']))
		{
			$title = addslashes($_POST['title']);
			$content = addslashes($_POST['content']);
			$full = (isset($_POST['full'])?addslashes($_POST['full']):'');
			$url = $this->core->translitUrl($title);
			if (isset($_POST['url']))
				if (!empty($_POST['url']))
					$url = $_POST['url'];
					
			$SQL = "UPDATE " . $this->tableName . " SET title='$title' , content='$content' , full='$full' , url='" .  $url . "' WHERE id='" . intval($_POST['id']) . "'";
			$this->core->db->executeQuery($SQL);
			
			$this->adminMain();
		}
	}
	
	//! Add news
	function adminAdd()
	{
		if (!isset($_POST['actAdmin']))
		{
		?>
		<h2>Добавить новость</h2>
		<form action="<?=basename($_SERVER['SCRIPT_FILENAME']);?>" method="POST">
		<input type="hidden" name="actAdmin" value="news">
		<input type="hidden" name="actionNews" value="Add">
		<table cellspacing="2" cellpadding="0" border="0">
		<TR><TD>Заголовок:</TD><TD><input type="text" name="title" value=""></TD></TR>
		<TR><TD>Текст:</TD><TD><textarea name="content"></textarea></TD></TR>
		<TR><TD>Расширенный текст:</TD><TD><textarea name="full"></textarea></TD></TR>
		<TR><TD>URL:</TD><TD><input type="text" name="url" value=""> (пусто для автоматической транслитеризации)</TD></TR>
		<TR><TD>Добавить:</TD><TD><input type="submit" value="Сохранить"></TD></TR>
		</table>
		</form><br />
		<a href="<?=basename($_SERVER['SCRIPT_FILENAME']);?>?actAdmin=news">Назад в новости</a>
		<?php
		}
		else
		{
			if (isset($_POST['title'],$_POST['content']))
			{
				$title = addslashes($_POST['title']);
				$content = addslashes($_POST['content']);
				$full = (isset($_POST['full'])?addslashes($_POST['full']):'');
				$url = $this->core->translitUrl($title);
				if (isset($_POST['url']))
					if (!empty($_POST['url']))
						$url = $_POST['url'];
						
				$SQL = "INSERT INTO " . $this->tableName . " ( title , content , full , date , url ) VALUES ( '$title' , '$content' , '$full' , '" . time() . "' , '" .  $url . "' )";
				$this->core->db->executeQuery($SQL);
				
				$this->adminMain();
			}
			else
			{
				echo ("Ошибка.");
			}
			
		}
	}
}
